package com.fizz.config;

import com.fizz.common.DataSourceTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Component
public class RoutingDataSourceImpl extends AbstractRoutingDataSource {


    @Override
    public void afterPropertiesSet() {
        this.setDefaultTargetDataSource(writeDataSource);
        Map<Object,Object> targetDataSource = new HashMap<Object,Object>();
        targetDataSource.put(DataSourceTypeEnum.READ_DATA_SOURCE.type,readDataSource);
        targetDataSource.put(DataSourceTypeEnum.WRITE_DATA_SOURCE.type,writeDataSource);
        this.setTargetDataSources(targetDataSource);
        super.afterPropertiesSet();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        String typeKey = DatasourceContextHolder.getReadOrWrite();
        Assert.notNull(typeKey,"数据库路由库为null，无法切换");
        logger.info("使用" + typeKey+ "数据库");
        return typeKey;
    }

    private static Logger log = LoggerFactory.getLogger(RoutingDataSourceImpl.class);

    @Autowired
    @Qualifier("writeDataSource")
    private DataSource writeDataSource;

    @Autowired
    @Qualifier("readDataSource")
    private DataSource readDataSource;

}
